import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.ResultSet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String DB_URL = "jdbc:mysql://124.70.48.17:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASS = "1qaz@WSX#EDC";

    static {
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("JDBC Driver not found", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");


        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
             PreparedStatement stmt = conn.prepareStatement("SELECT * FROM t_book");
             ResultSet rs = stmt.executeQuery()) {
            JSONArray books = new JSONArray();
            while (rs.next()) {
                JSONObject book = new JSONObject();
                book.put("number", rs.getString("number"));
                book.put("name", rs.getString("name"));
                book.put("author", rs.getString("author"));
                books.put(book);
            }
            out.println(books.toString());
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"message\": \"Error retrieving books\"}");
        }
    }
}
